<template>

  	<div class="x-warnitem">
		<div v-if="isName" class="warnitem-head">
			<div class="item-name">{{name}}</div>
			<div class="item-txt">{{ctx}}</div>
		</div>
		<vue-scroll :class-option="optionSetting" class="scroll-ctx" :class="{'scroll-h':isName}" :data="listData">
			<ul class="ctx-item">
				<li @click="onRowClick(item)" v-for="(item,index) in listData" class="item-li" :key="index">
					<span class="time">{{item.nowTime}}</span>

					<span class="txt">{{item.newAlarmTxt}}</span>
				</li>
			</ul>
		</vue-scroll>

    <warn-detail v-if="showDetail" @closeMask="closeMask" :detail="detail" :code="leader">

    </warn-detail>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible1"
      class="jk-dialog xmonitor1"
      style="z-index:10000;"
    >

       	<div style="width:786px;height:432px;margin:auto">
				<img :src="picurl |filterimgsrc" alt style="height:100%" />
			</div>
    </el-dialog>
	</div>


</template>
<script>
import jkData from "../xmonitor/data.json";
	import {
		GetAlarmsList,
    getAlarmInfo,
	} from "@/api/portalApi";
	import {
		GetDeviceLocationList,
    GetDeviceInfo,
    DevicesTypes,
    GetRedisDeviceInfo
	} from "@/api/device";
	import VueScroll from "vue-seamless-scroll";
	import json from '@/api/alarmcode'
  import picurls from "@/pages/portalmap/wulianicon.json";
  import WarnDetail from './detail'
	let jkLayer
	export default {
		name: "xwarnitem",
		data() {
			return {
        listData: [],
        unitTypeList: [],
        alarmcodeJson1: DevicesTypes(),
        alarmcodeJson: json,
        timer:null,
          dialogVisible1: false,
          dialogTitle: "",
          token: "",
          v1: null,
          picurl:'',
          detail:{},
          showDetail:false
			};
		},
		props: {
			newMap: {
				type: Object,
				default: {}
			},
			isName: {
				type: Boolean,
				default: true
			},
			name: {
				type: String,
				default: "预警时间"
			},
			ctx: {
				type: String,
				default: "预警内容"
			},
			id: {
				type: [String, Number, Object]
			},
			leader: {
				type: String,
			}
		},

		computed: {
			optionSetting() {
				return {
					step: 0.4, // 数值越大速度滚动越快

					limitMoveNum: 5, // 开始无缝滚动的数据量 this.dataList.length

					hoverStop: true, // 是否开启鼠标悬停stop

					direction: 1, // 0向下 1向上 2向左 3向右

					openWatch: true, // 开启数据实时监控刷新dom

					singleHeight: 0, // 单步运动停止的高度(默认值0是无缝不停止的滚动) direction => 0/1

					singleWidth: 0, // 单步运动停止的宽度(默认值0是无缝不停止的滚动) direction => 2/3

					waitTime: 1000 // 单步运动停止的时间(默认值1000ms)
				};
			}
		},
		components: {
      VueScroll,
      WarnDetail
		},

    mounted() {
       this.getAlarmsList();
      this.GetDictDataEnumList()
        if(this.timer){
          clearInterval(this.timer)
        }else{
          this.timer=setInterval(()=>{
            this.getAlarmsList();
          },18000000)
        }
    },
    destroyed(){
        console.log('destroyed')
        clearInterval(this.timer)
    },
		watch: {
			// leader: function() {
			// 	this.getAlarmsList();
			// }
		},
		methods: {
      closeMask(){
        this.showDetail=false
      },
			//点击
			async onRowClick(item) {
				console.log(item)
				// var lay=this.newMap.addLayer({
				//   id:"warnbox",
				//   type:"vector"
        // })
        this.showDetail=true
        this.detail=item
        if(item.type=="wulian"){
          this.removeMarker()

          this.addMapMarker([
            [item.deveui, item.deviceName, item.lX, item.lY, item.key, item.devtype, item.devtype]
          ])


        }
        if(item.type=="shexiangtou"){
          // this.showVideo(item.alarmPic)
        }


			},
			// 获取数据
			async getAlarmsList() {
				var _this = this;
				try {
					let params = {
						placeId: this.$storage.get('place').leader
					};
					if (this.id) {
						Object.assign(params, {
							id: this.id
						});
					}

					this.stop();
					let waringList = await GetAlarmsList(params);
					console.log("+++++" + JSON.stringify(waringList.data))
					let arr = []
					for (const key in waringList.data) {
						if (waringList.data.hasOwnProperty(key)) {
							const element = waringList.data[key];
							const json = eval("(" + element + ")")
							json["key"] = key
              const now = new Date(json.time)
              let year=now.getFullYear()
							let month = now.getMonth() + 1;
							month < 10 ? month = "0" + month : month = month;
							let date = now.getDate()
							date < 10 ? date = "0" + date : date = date;
							let hour = now.getHours()
							hour < 10 ? hour = "0" + hour : hour = hour;
							let minute = now.getMinutes()
							minute < 10 ? minute = "0" + minute : minute = minute;
							let seconds = now.getSeconds()
							seconds < 10 ? seconds = "0" + seconds : seconds = seconds;
							const nowTime = year + "-" + +month + "-" + date + " " + hour + ":" + minute + ":" + seconds;
              json["nowTime"] = nowTime
              json['type']='wulian' //判断是否是摄像头
							let devtype = json.devtype;
							let alarmcode = json.alarmcode;
              let codetype = json.codetype;
              let devName=""
							let newAlarmTxt = '';
							for (let i = 0; i < _this.alarmcodeJson.length; i++) {
								if (_this.alarmcodeJson[i].devtype == devtype && _this.alarmcodeJson[i].alarmcode == alarmcode && _this.alarmcodeJson[
										i].codetype == codetype) {
                  devName=_this.alarmcodeJson[i].devname
									newAlarmTxt = _this.alarmcodeJson[i].devname + "：" + _this.alarmcodeJson[i].alarmcodename
								}
              }
              json["devName"]=devName
              json["address"]=json.address
              json["newAlarmTxt"] = newAlarmTxt
              json["deviceType"]=json.devtype
              json["alarmCode"]=json.alarmcode
              if(json["newAlarmTxt"] !=''){
                	arr.push(json)
              }

							//arr.push({
							//  ...element,
							//  key
							//})
						}
					}

					let param = {}
					param.placeId = this.$storage.get('place').leader
					console.log("+_+_+" + JSON.stringify(param))
					let newAlarmList = await getAlarmInfo(param);
					console.log("+_+_+" + JSON.stringify(newAlarmList))

					for(let i=0;i<newAlarmList.data.length;i++){
            let newjson = {};

            newjson["nowTime"] = new Date().dateFtt(newAlarmList.data[i].alarmTime)

            // newjson["nowTime"] = newAlarmList.data[i].alarmTime.replace("T", " ").replace("Z", " ").substr(0, 19)
            newjson["address"]=newAlarmList.data[i].address
            newjson["newAlarmTxt"] = newAlarmList.data[i].address + "：" + newAlarmList.data[i].alarmType;
            newjson["id"]=newAlarmList.data[i].id
            newjson["alarmPic"]=newAlarmList.data[i].alarmPic
            newjson['type']='shexiangtou' //判断是否是摄像头
						arr.push(newjson);
					}
					this.listData = arr;
					console.log("+++" + JSON.stringify(this.listData))
					if (this.listData.length > 0) {
						this.play();
					}
				} catch (error) {
					console.log(error);
				}
			},
			change() {
				//change、paly表格数据动态滚动
				this.listData.push(this.listData[0]); //把第一条数据插入数组最有一条
				this.listData.shift(); //删除数组中第一条数据
			},
			play() {
				this.timer = setInterval(this.change, 2000); //每两秒执行一次插入删除操作
			},
			stop() {
				clearInterval(this.timer);
			},
			removeMarker() {
				this.newMap.removeLayer('warn')
			},
			addMapMarker(data) {
        let that = this;
        var _this=this;
				var lay = this.newMap.addLayer({
					id: "warn",
					type: "vector",
					events: {
						featureClick: function(f) {
							that.removeMarker()
            },
            featureMouseMove:function(f,e){
            var id="test"
            var position=[f.attributes.x,f.attributes.y]

            let p=new Promise((res,rej)=>{
              res(_this.getRedisDeviceInfo(f.attributes.type))
            })
            p.then(res=>{
              var template=''
              template+=_this.forObject(res,f.attributes.type[5])
              let element = document.createElement('div')
              element.style.zIndex="9999"
                element.innerHTML=template
                var closer=document.createElement('div')
                closer.innerHTML='<div class="close" ref="closebutton">X</div>'
                var positioning=['R','B']
                console.log('created')
                _this.newMap.addPopup(
                  id,
                  position,
                  element,
                  null,
                  positioning
                )
            })

          },
          featureMouseOut:function(f){
            setTimeout(()=>{
              _this.newMap.removePopup('test')
              _this.newMap.clearAllPopup()
              console.log('remove了')
            },1000)

          }
					}
				})
				this.drawPointsByVideo(data, lay);
				// jkLayer = new OMAP.Layer.Vector("jkLayer", {
				//   renderers: ["SVG"],
				//   eventListeners: {
				//     // 图层事件
				//     featureclick(e) {
				//       // 点击事件;

				//     },
				//     featureover: e => {
				//       // 移入事件
				//     },
				//     featureout: function(e) {
				//       // 移出事件
				//     }
				//   }
				// });

				// var features = this.drawPointsByVideo(data);
				// console.log(features);
				// jkLayer.addFeatures(features);
				// window.newMap.addLayer(jkLayer);
			},
			drawPointsByVideo(items, lay) {
				var that = this;
				var features = [];
				var x;
				var y;
				var pics = picurls.pic;
				for (var i = 0; i < items.length; i++) {
					var o = JSON.parse(JSON.stringify(items[i]));
					console.log("ooooo", o);
					var img
					// var img = require("../../assets/images/icon/svg" + o[6] + ".png");
					pics.map(item => {
						if (item.type == o[6]) {
							img = item.src;
						}
					});
					var style = {
						image: img,
						imageSize: [34, 76],
						imageCenter: ["C", "C"],
						imageOpacity: 1,
					};
					console.log("xxx", o[0]);
					let oo = {};
					oo.id = o[0];
					oo.name = o[1];
					oo.x = o[2];
					oo.y = o[3];
					oo.lon = o[2];
					oo.lat = o[3];
					oo.url = o[4];
					oo.num = i;
					// var feature = this.getPointFeature(oo, style);
					// features.push(feature);
					var feature = this.newMap.addFeatures(lay, "Point", [{
						x: o[2],
            y: o[3],
            type:o
					}]);
					style = that.newMap.createStyle(style);
					feature[0].setStyle(style);
					x = o[2];
					y = o[3];
				}
				return features;
			},
			getPointFeature(item, style) {
				console.log("item", item);
				var object = new OMAP.Geometry.Point(item.lon, item.lat);
				var typestr = "Point_" + item.id;
				var feature = new OMAP.Feature.Vector(object, item, style);
				feature.attributes.pid = typestr;
				return feature;
      },
    forObject(res,type){
      var template=''
      if(res==null || res.alarmcode){//报警
            template+='<div class="boxline"><div class="left">设备:</div><div class="right">'+this.switchDevices(res.devtype)+'</div></div>'
            template+='<div class="boxline"><div class="left">位置:</div><div class="right">'+res.location+'</div></div>'
            template+='<div class="boxline"><div class="left">时间:</div><div class="right">'+new Date().dateFtt1(res.time)+'</div></div>'
            template+='<div class="boxline"><div class="left">状态:</div><div class="right">'+"报警"+'</div></div>'

      }else{
          if(Object.keys(res).length != 0){
          if(type=='10'){
            template+='<div class="boxline"><div class="left">设备:</div><div class="right">小型气象站监测</div></div>'
            template+='<div class="boxline"><div class="left">位置:</div><div class="right">'+res.location+'</div></div>'
            template+='<div class="boxline"><div class="left">时间:</div><div class="right">'+new Date().dateFtt1(res.time)+'</div></div>'
            template+='<div class="boxline"><div class="left">温度:</div><div class="right">'+res.temp/10+'℃</div></div>'
            template+='<div class="boxline"><div class="left">湿度:</div><div class="right">'+res.hum/10+'%RH</div></div>'
            template+='<div class="boxline"><div class="left">风速:</div><div class="right">'+res.avgspeed/10+'m/s</div></div>'
            template+='<div class="boxline"><div class="left">雨量:</div><div class="right">'+res.rain/10+'mm</div></div>'
            template+='<div class="boxline"><div class="left">辐射:</div><div class="right">'+res.radiation/10+'w/m2</div></div>'
            template+='<div class="boxline"><div class="left">PM2.5:</div><div class="right">'+res['PM2.5']/10+'ug/m3</div></div>'
          }
          if(type=='1'){
            template+='<div class="boxline"><div class="left">设备:</div><div class="right">智能井盖</div></div>'
            template+='<div class="boxline"><div class="left">位置:</div><div class="right">'+res.location+'</div></div>'
            template+='<div class="boxline"><div class="left">时间:</div><div class="right">'+new Date().dateFtt1(res.time)+'</div></div>'
            template+='<div class="boxline"><div class="left">倾斜角度:</div><div class="right">'+res.angle+'度</div></div>'
          }
          if(type=='11'){
            template+='<div class="boxline"><div class="left">设备:</div><div class="right">水表</div></div>'
            template+='<div class="boxline"><div class="left">位置:</div><div class="right">'+res.location+'</div></div>'
            template+='<div class="boxline"><div class="left">时间:</div><div class="right">'+new Date().dateFtt1(res.time)+'</div></div>'
            template+='<div class="boxline"><div class="left">累计量:</div><div class="right">'+res.accum+'</div></div>'
          }
          if(type=='2'){
            template+='<div class="boxline"><div class="left">设备:</div><div class="right">可燃气体报警器</div></div>'
            template+='<div class="boxline"><div class="left">位置:</div><div class="right">'+res.location+'</div></div>'
            template+='<div class="boxline"><div class="left">时间:</div><div class="right">'+new Date().dateFtt1(res.time)+'</div></div>'
            template+='<div class="boxline"><div class="left">检测值:</div><div class="right">'+res.gasvalue+'％LEL</div></div>'
          }
          if(type=='3'){
            template+='<div class="boxline"><div class="left">设备:</div><div class="right">无线烟感</div></div>'
            template+='<div class="boxline"><div class="left">位置:</div><div class="right">'+res.location+'</div></div>'
            template+='<div class="boxline"><div class="left">时间:</div><div class="right">'+new Date().dateFtt1(res.time)+'</div></div>'
            template+='<div class="boxline"><div class="left">烟浓度值:</div><div class="right">'+res.SM+'</div></div>'
          }
          if(type=='5'){
            template+='<div class="boxline"><div class="left">设备:</div><div class="right">消防水压</div></div>'
            template+='<div class="boxline"><div class="left">位置:</div><div class="right">'+res.location+'</div></div>'
            template+='<div class="boxline"><div class="left">时间:</div><div class="right">'+new Date().dateFtt1(res.time)+'</div></div>'
            template+='<div class="boxline"><div class="left">水压:</div><div class="right">'+res.pressure+'Kpa</div></div>'
          }
          if(type=='7'){
            template+='<div class="boxline"><div class="left">设备:</div><div class="right">消防水箱液位监测</div></div>'
            template+='<div class="boxline"><div class="left">位置:</div><div class="right">'+res.location+'</div></div>'
            template+='<div class="boxline"><div class="left">时间:</div><div class="right">'+new Date().dateFtt1(res.time)+'</div></div>'
            template+='<div class="boxline"><div class="left">液位压力:</div><div class="right">'+res.hydraulic+'mm</div></div>'
          }
          if(type=='8'){
            template+='<div class="boxline"><div class="left">设备:</div><div class="right">水泵房漏水监测</div></div>'
            template+='<div class="boxline"><div class="left">位置:</div><div class="right">'+res.location+'</div></div>'
            template+='<div class="boxline"><div class="left">时间:</div><div class="right">'+new Date().dateFtt1(res.time)+'</div></div>'
            template+='<div class="boxline"><div class="left">液位:</div><div class="right">'+res.distance+'mm</div></div>'
          }
            if(type=='9'){
            template+='<div class="boxline"><div class="left">设备:</div><div class="right">水浸传感器</div></div>'
            template+='<div class="boxline"><div class="left">位置:</div><div class="right">'+res.location+'</div></div>'
            template+='<div class="boxline"><div class="left">时间:</div><div class="right">'+new Date().dateFtt1(res.time)+'</div></div>'
            template+='<div class="boxline"><div class="left">水浸状态:</div><div class="right">'+res.status=="0"?"安全":"报警"+'</div></div>'
          }
          if(type=='14'){
            template+='<div class="boxline"><div class="left">设备:</div><div class="right">污水井液位监测</div></div>'
            template+='<div class="boxline"><div class="left">位置:</div><div class="right">'+res.location+'</div></div>'
            template+='<div class="boxline"><div class="left">时间:</div><div class="right">'+new Date().dateFtt1(res.time)+'</div></div>'
            template+='<div class="boxline"><div class="left">液位:</div><div class="right">'+res.distance+'mm</div></div>'
          }
        }
      }


      return template

    },
      //获取类型
    GetDictDataEnumList() {
      var data = {};
      var arr = [];
      this.alarmcodeJson1.map(item => {
        let name = item.devname;
        data[name] = item.devtype;
        // Object.assign(data, { name: item.devtype });
      });
      for (var i in data) {
        arr.push({
          enumName: i,
          id: data[i]
        });
      }
      this.unitTypeList = arr;

    },
    switchDevices(id){
      var name=''
      console.log(this.unitTypeList)
      this.unitTypeList.map(item=>{
        if(item.id==id){
          name=item.enumName
        }
      })
      return name
    },
    showVideo(id){
      console.log(id)
      this.dialogVisible1=true;
      // this.picurl=id
    },
    async getRedisDeviceInfo(data){
      var arg={
        placeId:this.leader,
        deviceType:data[5],
        deviceId:data[0]
      }
      console.log(arg)
      var res=await GetRedisDeviceInfo(arg)
      return res
    }
    }

	};
</script>

<style lang="less" scoped>
.boxline{
  background: rgba(9,15,31);
  color:#fff;
  border:1px solid rgba(94,177,211);
  line-height: 25px;
  height:27px;
  text-align: left;
  width: 250px;
  display: flex;
  z-index: 11111;
  .left{
    width: 100px;
  }
  .right{
    width:190px
  }
}
	.x-warnitem {
		width: 100%;
		height: 100%;
		padding: 0 18px;
		box-sizing: border-box;

		.warnitem-head {
			width: 100%;
			height: 28px;
			display: flex;
			justify-content: space-around;
			align-items: center;
			font-size: 11px;
			color: #fff;

			.item-name {
				flex: 1.1;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				word-break: normal;
				text-align: left;
				font-size: 14px;
			}

			.item-txt {
				flex: 2;
				padding-left: 20px;
				box-sizing: border-box;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				word-break: normal;
				text-align: left;
				font-size: 14px;
			}
		}

		.scroll-ctx {
			width: 100%;
			height: 100%;
			overflow: hidden;

			&.scroll-h {
				height: calc(100% - 28px);
			}

			.ctx-item {
				width: 100%;
				height: 100%;
				margin: 0;
				padding: 0;
				list-style: none;

				.item-li {
					width: 100%;
					display: flex;
					justify-content: space-around;
					align-items: center;
					height: 28px;
					margin: 0;
					padding: 0;
					font-size: 14px;
					color: #fff;
					cursor: pointer;

					.time {
						flex: 1.1;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
						word-break: normal;
						text-align: left;
						font-size: 14px;
					}

					.txt {
						flex: 2;
						padding-left: 20px;
						box-sizing: border-box;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
						word-break: normal;
						text-align: left;
						font-size: 14px;
					}
				}
			}
		}
	}

	.scroll {
		width: 100%;
		height: 100%;
		overflow: hidden;

		.animatedTop {
			transition: all 0.5s linear;
		}

		ul,
		li {
			list-style: none;
			padding: 0;
			margin: 0;
		}

		li {
			width: 100%;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
			margin-bottom: 5px;
		}
	}
</style>
